#include "render.h"

#ifdef DEBUG
#include <iostream>
#endif

#include <boost/foreach.hpp>

#define bforeach BOOST_FOREACH

namespace Ui {

Render::Render(QWidget* _parent) : QGLWidget(_parent), triangulation_visualization(true), points_visualization(true), viewport_scale(10), triangulation_object(0) { 
}
Render::~Render(void) {
	makeCurrent();
	if(triangulation_object) glDeleteLists(triangulation_object, 1);
} 


QSize Render::minimumSizeHint(void) const {
	return QSize(100, 100);
}

QSize Render::sizeHint(void) const {
	return QSize(400, 400);
}

void Render::set_points(std::vector<Tut::Vector> _points) {
	points = _points;
	updateGL();
}
void Render::set_triangulation(std::vector<Tut::Edge> _triangulation) {
	if(triangulation_object) glDeleteLists(triangulation_object, 1);
	triangulation = _triangulation;
	GLuint list = glGenLists(1);
	glNewList(list, GL_COMPILE);
	glBegin(GL_LINES);
	bforeach(Tut::Edge point, triangulation) {
		glVertex2d(point.point1.x, point.point1.y);
		glVertex2d(point.point2.x, point.point2.y);
		std::cout << "." << std::endl;
	}
	glEnd();

	glColor3d(0.0,0.0,0.0);
/*
	bforeach(std::vector<Tujchi::Vector> pointss, convex_hull) {
		bool flag = false;
		Tujchi::Vector last_point;
		glBegin(GL_LINE_LOOP);
		bforeach(Tujchi::Vector point, pointss) {
			if(flag)
				glVertex2d(last_point.x, last_point.y);
			else flag = true;
			last_point = point;
			glVertex2d(point.x, point.y);
		}
		glEnd();
	}
*/
	glEndList();
	triangulation_object = list;
	updateGL();
}

void Render::clear_points(void) {
	triangulation.clear();
}

void Render::clear_triangulation(void) {
	triangulation.clear();
}

void Render::set_points_visualization(bool option) {
	points_visualization = option;
	updateGL();
}
void Render::set_triangulation_visualization(bool option) {
	triangulation_visualization = option;
	updateGL();
}
void Render::set_viewport_scale(int scale) {
	viewport_scale = scale;
	updateGL();
}
void Render::initializeGL(void) {
	glShadeModel(GL_FLAT);
	glDisable(GL_DEPTH_TEST);
	glPointSize(5);
	glLineWidth(3);
}

void Render::paintGL(void) {
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-viewport_scale, +viewport_scale, -viewport_scale, +viewport_scale, 4.0, 15.0);
	glMatrixMode(GL_MODELVIEW);
	glClearColor(0.6,0.6,0.6,1.0);
	glClear(GL_COLOR_BUFFER_BIT );
	glLoadIdentity();
	glTranslated(0.0, 0.0, -10.0);
	if(points_visualization) {
		glColor3d(0.0,1.0,0.0);
		glBegin(GL_POINTS);
		bforeach(Tut::Vector point , points) {
			glVertex2d(point.x, point.y);
		}
		glEnd();
	}
	if(triangulation_visualization) {
		glColor3d(1.0,0.0,0.0);
		if(triangulation_object)
			glCallList(triangulation_object);
	}
}

void Render::resizeGL(int width, int height) {
	int side = qMin(width, height);
	glViewport((width - side) / 2, (height - side) / 2, side, side);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-viewport_scale, +viewport_scale, -viewport_scale, +viewport_scale, 4.0, 15.0);
	glMatrixMode(GL_MODELVIEW);
}








}

